package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired(required = false)
    private EmployeeMapper employeeMapper;

    @Override
    //员工登录
    public R<Employee> login(Employee employee) {
//        ①. 根据页面提交的用户名username查询数据库中员工数据信息
       Employee dbEmployee = employeeMapper.login(employee);

//        ②. 如果没有查询到, 则返回登录失败结果
        if (dbEmployee==null){
            return R.error("用户名不存在");
        }
//        ③. 密码比对，如果不一致, 则返回登录失败结果
        //将明文密码转换为md5密码，然后才能进行对比
        String md5Password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if(!md5Password.equals(dbEmployee.getPassword())){
            return R.error("密码错误");
        }

//        ④. 查看员工状态，如果为已禁用状态，则返回员工已禁用结果
        if (dbEmployee.getStatus()==0){
            return R.error("用户名已被禁用");
        }
        return R.success(dbEmployee);
    }

    @Override
    //添加员工
    public void insert(Employee employee) {
        //补全除登录数据以外的信息
        employee.setPassword(DigestUtils.md5DigestAsHex("1202".getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //把数据交给mapper插入
        employeeMapper.insert(employee);
    }

    @Override
    //
    public Page<Employee> findBypage(Integer page, Integer pageSize, String name) {
        //1.设置当前页面和页面大小
        PageHelper.startPage(page,pageSize);

        //2.根据名字查询数据
        List<Employee> employeeList = employeeMapper.findByName(name);

        //3.创建PageINfo对象，把list集合传入
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);

        //4.把pageinfo的信息转移到Page对象
        Page<Employee> pageResult = new Page<>(pageInfo.getList(),pageInfo.getTotal(),pageInfo.getPageSize(),pageInfo.getPageNum());
        return pageResult;
    }

    @Override
    public void update(Employee employee) {
         employee.setUpdateTime(LocalDateTime.now());
         employeeMapper.update(employee);
    }

    @Override
    public R<Employee> findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        return R.success(employee);
    }
}
